<template>
  <div class='ele-body ele-body-card'>
    <!-- 顶部卡片 -->
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='form'
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='checkAndPushSubmitConfig'
      >
        <a-divider orientation="left">基础设置</a-divider>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label="和服务器的连接方式:" name="reportModel">
              <a-select v-model:value="form.reportModel">
                <a-select-option :value="0">Stop reporting</a-select-option>
                <a-select-option :value="1">TCP short-connection preferred mode</a-select-option>
                <a-select-option :value="2">TCP short-connection forced mode</a-select-option>
                <a-select-option :value="3">TCP long-connecton mode</a-select-option>
                <a-select-option :value="4">UDP mode</a-select-option>
                <a-select-option :value="5">Force on SMS</a-select-option>
                <a-select-option :value="6">UDP with fixed local port</a-select-option>
                <a-select-option :value="7">TCP long-connection mode with the backup server</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-divider orientation="left">SIM卡或LTE或GPRS设置</a-divider>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='APN:' name='apnChannel'>
              <a-input v-model:value='form.apnChannel' placeholder='请输入APN' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='APN用户名字:' name='apnUserName'>
              <a-input v-model:value='form.apnUserName' placeholder='请输入APN用户名字' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='APN用户密码:' name='apnPassword'>
              <a-input v-model:value='form.apnPassword' placeholder='请输入APN用户密码' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-divider orientation="left">服务器连接设置</a-divider>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='主服务器域名或IP:' name='mainServerIp'>
              <a-input v-model:value='form.mainServerIp' placeholder='请输入主服务器域名或IP' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='主服务器的端口:' name='mainServerPort'>
              <a-input-number :min="0" :max="65535" v-model:value='form.mainServerPort' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='备份服务器域名或IP:' name='backupServerIp'>
              <a-input v-model:value='form.backupServerIp' placeholder='请输入备份服务器域名或IP' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='备份服务器的端口:' name='backupServerPort'>
              <a-input-number :min="0" :max="65535" v-model:value='form.backupServerPort' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='SMS网关:' name='smsGateway'>
              <a-input v-model:value='form.smsGateway' placeholder='请输入SMS网关' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-divider orientation="left">其他设置</a-divider>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='心跳频率(分钟):' name='heartbeat'>
              <a-input-number :min="0" :max="360" v-model:value='form.heartbeat' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label="服务器ACK机制:" name="sack">
              <a-select v-model:value="form.sack">
                <a-select-option :value="0">禁止SACK</a-select-option>
                <a-select-option :value="1">接收SACK并且确认</a-select-option>
                <a-select-option :value="2">接收SACK但不确认</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label="SMS-ACK机制:" name="smsAck">
              <a-select v-model:value="form.smsAck">
                <a-select-option :value="0">禁止SMS ACK</a-select-option>
                <a-select-option :value="1">开启SMS ACK</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label="缓冲区模式:" name="bufferModel">
              <a-select v-model:value="form.bufferModel">
                <a-select-option :value="0">禁用</a-select-option>
                <a-select-option :value="1">低优先级</a-select-option>
                <a-select-option :value="2">高优先级</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>
        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label="协议类型:" name="protocol">
              <a-select v-model:value="form.protocol">
                <a-select-option :value="0">ASCII format</a-select-option>
                <a-select-option :value="1">HEX format</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='14' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='8' :sm='24' :xs='24'>
            <a-button type='primary' html-type='submit' :loading='formSubmitLoading'>
              提交
            </a-button>
            <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='readQSS' :loading='readLoading'>
              读取
            </a-button>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'></a-col>
        </a-row>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import {VehicleConfigServerConnectionApi} from "@/api/property/vechile/VehicleConfigServerConnectionApi";

export default {
  name: 'DeviceVehicleConfigConnection',
  components: {

  },
  props: {
    data: Object
  },
  async created() {
    this.getDetail();
  },
  data() {
    return {
      form : {},
      currentConfig : {},
      loading : false,

      formSubmitLoading : false,
      formSubmitTimer : undefined,

      readLoading : false,
      readTimer : undefined
    };
  },
  methods: {
    getDetail() {
      let that = this;
      VehicleConfigServerConnectionApi.detail({"recordId" : this.data.recordId}).then(result => {
        that.form = result || {};
        that.currentConfig = JSON.parse(JSON.stringify(result || {}));
      });
    },

    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail2(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //-------提交
    clearSubmitConfig(){
      this.formSubmitLoading = false;
      clearInterval(this.formSubmitTimer);
    },

    checkSubmitConfig(){
      let that = this;
      this.checkProcess(1, this.clearSubmitConfig, function(){
        that.getDetail();
      });
    },

    checkAndPushSubmitConfig() {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 1
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitConfigSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitConfigSubmit() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({ old: this.currentConfig, update: this.form}),
        dictate : 1, //AT+GTQSS=
        sceneDictate : 1 //服务器连接配置
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.formSubmitLoading = true; //转圈
          this.formSubmitTimer = setInterval(this.checkSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //-------读取数据
    clearReadSubmitConfig(){
      this.readLoading = false;
      clearInterval(this.readTimer);
    },

    checkReadSubmitConfig(){
      let that = this;
      this.checkProcess(600, this.clearReadSubmitConfig, function(){
        that.getDetail();
      });
    },

    readQSS() {
      let workerDetailParams = {
        recordId: this.data.recordId,
        sceneDictate: 600
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailParams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitReadSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitReadSubmit() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({}),
        dictate : 600, //读取QSS
        sceneDictate : 600
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.readLoading = true; //转圈
          this.readTimer = setInterval(this.checkReadSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },



  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
